package com.stormrage.edu.ctrl.exam;

import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.stormrage.edu.serv.adm.AdmAcctServ;
import com.stormrage.edu.serv.edu.EduModuleServ;
import com.stormrage.edu.serv.exam.ExmAnswerServ;
import com.stormrage.edu.serv.exam.ExmExamServ;
import com.stormrage.entity.adm.AdmRes;
import com.stormrage.entity.edu.rep.EduModuleRep;
import com.stormrage.entity.exam.ExmAnswer;
import com.stormrage.entity.exam.ExmExam;
import com.stormrage.entity.exam.rep.ExmAnswerRep;
import com.stormrage.entity.exam.req.ExmExamReq;
import com.stormrage.entity.rep.ErrorRep;
import com.stormrage.entity.rep.JsonRep;
import com.stormrage.entity.rep.ListRep;
import com.stormrage.entity.shiro.ShiroAcct;
import com.stormrage.shiro.bind.CurrentUser;
import com.stormragetech.core.ctrl.BaseCtrl;
import com.stormragetech.core.entity.Page;

/**
 * @Title: ExamModuleCtrl.java
 * @Package com.stormrage.edu.ctrl.exam
 * @Description: 考试 课组 Controller
 * @author www.stormragetech.com
 * @date 2016年4月24日
 * @version V1.0
 */
@Controller
@RequestMapping("/exam/mod")
public class ExmModuleCtrl extends BaseCtrl {

	private static final Logger logger = LoggerFactory.getLogger(ExmModuleCtrl.class);

	@Value("#{constants['html.title']}")
	private String htmlTitle;

	@Autowired
	private AdmAcctServ admAcctServ;

	@Autowired
	private EduModuleServ eduModuleServ;

	@Autowired
	private ExmExamServ exmExamServ;

	@Autowired
	private ExmAnswerServ exmAnswerServ;

	@RequiresPermissions("exam:create")
	@RequestMapping(value = "/{aid}/{id}/list")
	public String list(@CurrentUser ShiroAcct curr, @PathVariable("aid") Integer aid, @PathVariable("id") Integer id,
			Model model) {

		logger.debug(" 【 Controller 】-【 ExamModuleCtrl 】-【 List 】-【 POST 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			List<EduModuleRep> array = eduModuleServ.queryListForExam(id);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("id", aid);
			model.addAttribute("data", array);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 ExamModuleCtrl 】-【 List 】-【 GET 】- 结束运行 ");
		return "exam/mod/list";
	}

	@RequiresPermissions("exam:create")
	@RequestMapping(value = "/{aid}/{bid}/{id}/create", method = RequestMethod.GET)
	public String create(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, Model model) {

		logger.debug(" 【 Controller 】-【 ExmCourseCtrl 】-【 create 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("id", id);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 ExmCourseCtrl 】-【 create 】-【 GET 】- 结束运行 ");
		return "exam/mod/exam/create";
	}

	@RequiresPermissions("exam:create")
	@RequestMapping(value = "/{aid}/{bid}/{id}/create", method = RequestMethod.POST)
	public String create(@CurrentUser ShiroAcct curr, ExmExam entity, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 ExmCourseCtrl 】-【 Create 】-【 POST 】- 开始运行 ");

		logger.debug(" 试题的参数为 " + entity.toString());

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------

			Integer index = exmExamServ.create(entity);
			errMsg = "提示信息：添加编号为【 " + index + " 】的试题成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：添加试题失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/exam/mod/{aid}/{bid}/{id}/create";
		}

		logger.debug(" 【 Controller 】-【 ExmCourseCtrl 】-【 Create 】-【 POST 】- 结束运行 ");
		return "redirect:/exam/mod/{aid}/{bid}/{id}/exam";

	}

	@RequiresPermissions("exam:edit")
	@RequestMapping(value = "/{aid}/{bid}/{cid}/{id}/edit", method = RequestMethod.GET)
	public String edit(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, Model model) {

		logger.debug(" 【 Controller 】-【 ExmCourseCtrl 】-【 edit 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			ExmExam entity = exmExamServ.queryById(id);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("data", entity);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 ExmCourseCtrl 】-【 edit 】-【 GET 】- 结束运行 ");
		return "exam/mod/exam/edit";
	}

	@RequiresPermissions("exam:edit")
	@RequestMapping(value = "/{aid}/{bid}/{cid}/{id}/edit", method = RequestMethod.POST)
	public String edit(@CurrentUser ShiroAcct curr, ExmExam entity, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 ExmCourseCtrl 】-【 edit 】-【 POST 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------

			exmExamServ.update(entity);
			errMsg = "提示信息：修改编号为【 " + entity.getId() + " 】的试题成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：修改编号为【 " + entity.getId() + " 】的试题失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/exam/mod/{aid}/{bid}/{cid}/{id}/edit";
		}

		logger.debug(" 【 Controller 】-【 ExmCourseCtrl 】-【 edit 】-【 POST 】- 结束运行 ");
		return "redirect:/exam/mod/{aid}/{bid}/{cid}/exam";

	}

	@RequiresPermissions("exam:del")
	@RequestMapping(value = "/{aid}/{bid}/{cid}/{id}/del", method = RequestMethod.GET)
	public String delete(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 ExmCourseCtrl 】-【 delete 】-【 GET 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------

			exmExamServ.delete(id);
			errMsg = "提示信息：删除编号为【 " + id + " 】的试题成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：删除编号为【 " + id + " 】的试题失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/exam/mod/{aid}/{bid}/{cid}/exam";
		}

		logger.debug(" 【 Controller 】-【 ExmCourseCtrl 】-【 delete 】-【 GET 】- 结束运行 ");
		return "redirect:/exam/mod/{aid}/{bid}/{cid}/exam";

	}

	@RequiresPermissions("exam:view")
	@RequestMapping(value = "/{aid}/{bid}/{id}/exam")
	public String exam(@CurrentUser ShiroAcct curr, ExmExamReq req, Model model) {

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 exam 】-【 GET | POST 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			String search = JSON.toJSONString(req);

			logger.debug(" 查询条件req变为search为 " + search);

			if (null != search && search.length() > 0)
				model.addAttribute("search", search);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("form", req);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 List 】-【 GET | POST 】- 结束运行 ");
		return "exam/mod/exam/list";
	}

	@RequiresPermissions("chap:view")
	@RequestMapping(value = "/{aid}/{bid}/{id}/ajax", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String ajax(@PathVariable("id") Integer id, @RequestParam(value = "draw", required = true) Integer draw,
			@RequestParam(value = "start", required = true) Integer start,
			@RequestParam(value = "length", required = true) Integer length, ExmExamReq req) {

		logger.debug(" 【 Controller 】- 【 EduChapterCtrl 】- 【 Ajax 】-【 POST 】-【 STARTED 】");

		String json = null;

		try {

			// ------------------ 获取初始化模块的状态 ------------------
			Page page = Page.instance(start, length, 1);
			req = ExmExamReq.instance(req, 1, id, page);
			draw += 1;

			logger.debug(" 查询条件为 " + req.toString());

			ListRep entity = exmExamServ.queryListByRelateLimit(req);

			JsonRep rep = JsonRep.instance(entity.getCount(), draw, entity.getList());
			json = JSON.toJSONString(rep);

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 返回的json为 " + json);
		logger.debug(" 【 Controller 】- 【 EduChapterCtrl 】- 【 Ajax 】-【 POST 】-【 COMPLETED 】");
		return json;

	}

	@RequiresPermissions("exam:create")
	@RequestMapping(value = "/{aid}/{bid}/{cid}/{id}/create", method = RequestMethod.GET)
	public String asCreate(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, Model model) {

		logger.debug(" 【 Controller 】-【 ExmCourseCtrl 】-【 asCreate 】-【 GET 】-【 STARTED 】");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("id", id);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 ExmCourseCtrl 】-【 asCreate 】-【 GET 】-【 COMPLETED 】");
		return "exam/mod/exam/answer/create";
	}

	@RequiresPermissions("exam:create")
	@RequestMapping(value = "/{aid}/{bid}/{cid}/{id}/create", method = RequestMethod.POST)
	public String asCreate(@CurrentUser ShiroAcct curr, ExmAnswer entity, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 ExmCourseCtrl 】-【 asCreate 】-【 POST 】- 开始运行 ");

		logger.debug(" 试题的参数为 " + entity.toString());

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------

			exmAnswerServ.create(entity);
			errMsg = "添加ID为【" + entity.getExamId() + "】的试题的答案成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：添加ID为【" + entity.getExamId() + "】的试题的答案失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/exam/mod/{aid}/{bid}/{cid}/{id}/create";
		}

		logger.debug(" 【 Controller 】-【 ExmCourseCtrl 】-【 asCreate 】-【 POST 】- 结束运行 ");
		return "redirect:/exam/mod/{aid}/{bid}/{cid}/{id}/answer";

	}

	@RequiresPermissions("exam:edit")
	@RequestMapping(value = "/{aid}/{bid}/{cid}/{did}/{id}/edit", method = RequestMethod.GET)
	public String asEdit(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, Model model) {

		logger.debug(" 【 Controller 】-【 ExmCourseCtrl 】-【 asEdit 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			ExmAnswer entity = exmAnswerServ.queryById(id);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("data", entity);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 ExmCourseCtrl 】-【 asEdit 】-【 GET 】- 结束运行 ");
		return "exam/mod/exam/answer/edit";
	}

	@RequiresPermissions("exam:edit")
	@RequestMapping(value = "/{aid}/{bid}/{cid}/{did}/{id}/edit", method = RequestMethod.POST)
	public String asEdit(@CurrentUser ShiroAcct curr, ExmAnswer entity, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 ExmCourseCtrl 】-【 asEdit 】-【 POST 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------

			exmAnswerServ.update(entity);
			errMsg = "提示信息：修改编号为【 " + entity.getId() + " 】的答案成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：修改编号为【 " + entity.getId() + " 】的答案失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/exam/mod/{aid}/{bid}/{cid}/{did}/{id}/edit";
		}

		logger.debug(" 【 Controller 】-【 ExmCourseCtrl 】-【 asEdit 】-【 POST 】- 结束运行 ");
		return "redirect:/exam/mod/{aid}/{bid}/{cid}/{did}/answer";

	}

	@RequiresPermissions("exam:del")
	@RequestMapping(value = "/{aid}/{bid}/{cid}/{did}/{id}/del", method = RequestMethod.GET)
	public String asDelete(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 ExmCourseCtrl 】-【 asDelete 】-【 GET 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------

			exmAnswerServ.delete(id);
			errMsg = "提示信息：删除编号为【 " + id + " 】的答案成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：删除编号为【 " + id + " 】的答案失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/exam/mod/{aid}/{bid}/{cid}/{did}/answer";
		}

		logger.debug(" 【 Controller 】-【 ExmCourseCtrl 】-【 asDelete 】-【 GET 】- 结束运行 ");
		return "redirect:/exam/mod/{aid}/{bid}/{cid}/{did}/answer";

	}

	@RequiresPermissions("exam:view")
	@RequestMapping(value = "/{aid}/{bid}/{cid}/{id}/answer")
	public String answer(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, Model model) {

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 List 】-【 POST 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			List<ExmAnswerRep> array = exmAnswerServ.queryRepListByExamId(id);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("data", array);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 List 】-【 GET 】- 结束运行 ");
		return "exam/mod/exam/answer/list";
	}

}
